package org.ldx.lotterysystem.service.impl;

import jakarta.annotation.Resource;
import org.ldx.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.ldx.lotterysystem.common.exception.ServiceException;
import org.ldx.lotterysystem.common.utils.MailUtil;
import org.ldx.lotterysystem.common.utils.MyCaptchaUtil;
import org.ldx.lotterysystem.common.utils.RedisUtil;
import org.ldx.lotterysystem.common.utils.RegexUtil;
import org.ldx.lotterysystem.service.VerificationCodeService;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Resource
    RedisUtil redisUtil;
    @Resource
    MailUtil mailUtil;
    /**
     * 对redis中的key加前缀，用以区分业务
     */
    public static final String VERIFICATION_CODE_HEAD = "VerificationCode";
    @Override
    public void sendVerificationCode(String mail) {
        //检验邮箱号
        if(!RegexUtil.checkMail(mail)){
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        //生成并获取随机验证码
        String code = MyCaptchaUtil.getCaptcha(4);
        //发送验证码(邮箱发送)
        sendMail(mail,code);
        //存储验证码 60秒过期
        redisUtil.set(VERIFICATION_CODE_HEAD+mail,code,60L);
    }

    private void sendMail(String mail,String code) {
        mailUtil.sendSampleMail(mail,"验证码",mail+"您的验证码是:"+code);
    }

    @Override
    public String getVerificationCode(String mail) {
        //检验邮箱号
        if(!RegexUtil.checkMail(mail)){
            System.out.println("获取验证码检验邮箱出错----");
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_HEAD+mail);
    }
}
